package com.ruix.app.ui.stratum.lesson;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.ruix.app.R;
import com.ruix.app.RuiApplication;
import com.ruix.app.model.LessonInfo;
import com.ruix.app.service.MusicPlayerLisenter;
import com.ruix.app.service.MusicService;
import com.ruix.app.ui.adapter.LessonPicViewAdapter;
import com.ruix.app.ui.base.BaseActivity;
import com.ruix.app.util.DateUtil;
import com.ruix.app.util.LogUitl;

/**
 * Created by hadexs on 2017/5/11.
 */

public class FullScreenAudioActivity extends BaseActivity implements View.OnClickListener,SeekBar.OnSeekBarChangeListener,MusicPlayerLisenter {

    public static Intent newIntent(Context context, LessonInfo lessonInfo,int currentPage) {
        Intent intent = new Intent(context, FullScreenAudioActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("LessonInfo", lessonInfo);
        bundle.putInt("currentPage",currentPage);
        intent.putExtras(bundle);
        return intent;
    }

    private LessonInfo lessonInfo;
    private ViewPager viewPager;
    private TextView picCount,leftTime,startTimeView;
    private SeekBar seekBar;
    private ImageView playView;

    private LessonPicViewAdapter pagerAdapter;
    private int pageSize;
    private int currentPage;
    private int seekProgress; //滑动的进度
    private int lastProgress; //
    private boolean prepared;
    private String totalSecendsTime;
    private MusicService musicService;



    @Override
    protected boolean isUseBaseTitleBar() {
        return false;
    }

    private void initCarrayData(){
        Intent intent = getIntent();
        if (intent != null) {
            lessonInfo = (LessonInfo) intent.getSerializableExtra("LessonInfo");
            currentPage = intent.getIntExtra("currentPage",0);
        }
    }

    @Override
    protected void beforeOnCreate() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏标题
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
    }

    @Override
    protected int loadViewLayout() {
        return R.layout.activity_full_screen_audio;
    }

    @Override
    protected void initView() {
        initCarrayData();
        viewPager = (ViewPager)findViewById(R.id.picture_pager);
        picCount = (TextView) findViewById(R.id.tv_pic_count);
        leftTime = (TextView) findViewById(R.id.tv_left_time);
        seekBar = (SeekBar) findViewById(R.id.adiuo_seek_bar);
        playView = (ImageView) findViewById(R.id.btn_start_play);
        startTimeView = (TextView) findViewById(R.id.tv_create_time);
        seekBar.setMax(100);
        pagerAdapter = new LessonPicViewAdapter(this);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(3);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setCurrentPicCount(position ,pageSize);

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        if (lessonInfo != null){
            if (lessonInfo.getAlbum() != null && lessonInfo.getAlbum().size() > 0) {
                pageSize = lessonInfo.getAlbum().size();
                setCurrentPicCount(currentPage, pageSize);
                pagerAdapter.setPicAddress(lessonInfo.getAlbum());
                viewPager.setCurrentItem(currentPage);
            }
        }

        musicService = RuiApplication.getInstance().getMusicService();
        if (musicService != null) {
            musicService.addLisenter(this);
        }

        setLetTimeAndSeekBar();
        //判断如果为准备
    }




    private void setCurrentPicCount(int index,int total){
        this.currentPage = index;
        int indexnum = index +1 ;
        picCount.setText(indexnum+"/"+total);
    }



    @Override
    protected void initListener() {
        playView.setOnClickListener(this);
        seekBar.setOnSeekBarChangeListener(this);
        findViewById(R.id.btn_full_screen).setOnClickListener(this);

    }

    private void setAduioPayingState(){
        playView.setBackgroundResource(R.drawable.lession_aduio_pause);
    }

    private void setAduioPausedState(){
        if (playView != null) {
            playView.setBackgroundResource(R.drawable.audio_start_bg);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_start_play:
                if (lessonInfo !=null && musicService != null) {
                    if (musicService.isPreparing()) {
                        musicService.prepareUrl(lessonInfo.getAudio());
                        showErrorTip("加载中请稍后");
                    } else {
                        if (musicService.isPlaying()) {
                            musicService.pause();
                            setAduioPausedState();
                        } else {
                            musicService.start();
                            setAduioPayingState();
                        }
                    }
                }

                break;

            case R.id.btn_full_screen:
                setResultCount();
                break;
        }

    }

    private void setResultCount(){
        Intent intent = new Intent();
        intent.putExtra("currentPage",currentPage);
        setResult(RESULT_OK,intent);
        finish();
    }

    public void onBackPressed() {
        setResultCount();
        super.onBackPressed();
    }


    @Override
    protected void initLocalData() {

    }



    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        lastProgress =  seekBar.getProgress();
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (musicService != null){
            if (musicService.isPlaying()) {
                int duration = musicService.getDuration();
                if (duration > 0) {
                    int progress = seekBar.getProgress();
                    this.seekProgress = progress * duration / seekBar.getMax();
                    musicService.seekTo(seekProgress);
                }
            } else if (musicService.isPreparing()){
                seekBar.setProgress(lastProgress);
            } else {
                int duration = musicService.getDuration();
                if (duration > 0) {
                    int progress = seekBar.getProgress();
                    this.seekProgress = progress * duration / seekBar.getMax();
                    musicService.seekTo(seekProgress);
                    musicService.start();
                }

            }
        }

    }


    @Override
    public void onSeekComplete(MediaPlayer mp) {
        totalSecendsTime =  DateUtil.millisecondToMinute(mp.getDuration());
        String currentPosition  =  DateUtil.millisecondToMinute(mp.getCurrentPosition());
        leftTime.setText(currentPosition+"/"+totalSecendsTime);
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {

    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        prepared = true;
        if (mp.getDuration() > 0) {
            totalSecendsTime =  DateUtil.millisecondToMinute(mp.getDuration());
            leftTime.setText("00:00"+"/"+totalSecendsTime);
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        setAduioPausedState();
        if (seekBar != null) {
            seekBar.setProgress(0);
        }
        if (leftTime != null) {
            leftTime.setText("00:00" + "/" + totalSecendsTime);
        }
    }

    @Override
    public void onPlayerTick(int duration, int crrentPostion) {
        if (crrentPostion < duration) {
            totalSecendsTime = DateUtil.millisecondToMinute(duration);
            String currentPositionStr = DateUtil.millisecondToMinute(crrentPostion);
            leftTime.setText(currentPositionStr + "/" + totalSecendsTime);
            float progress = (float) crrentPostion / (float) duration * 100;
            seekBar.setProgress((int) progress);
        } else {
            if (musicService!= null) {
                musicService.seekTo(0);
            }
        }
    }

    @Override
    public void getCacheProgress(int progress) {

    }


    private void setLetTimeAndSeekBar(){
        if (musicService != null){
            int duration =musicService.getDuration();
            int crrentPostion = musicService.getCurrentPosition();
            onPlayerTick(duration,crrentPostion);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (musicService != null) {
            musicService.removeLisenter(this);
        }
    }
}
